package com.zmn.oms.dubbo.impl.zmn.factory.order;

import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.oms.common.constant.ConfOrderDutyConsts;
import org.apache.dubbo.config.annotation.Service;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.oms.business.interfaces.order.DuplicateOrderBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderGateTypeConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.*;
import com.zmn.oms.dubbo.dto.zmn.order.factory.CheckReworkOrderDIO;
import com.zmn.oms.dubbo.dto.zmn.order.factory.UpdateOrderDIO;
import com.zmn.oms.dubbo.dto.zmn.order.factory.*;
import com.zmn.oms.dubbo.dto.zmn.order.factory.detail.FcOrderDetailDRO;
import com.zmn.oms.dubbo.dto.zmn.order.factory.detail.OrderPostDRO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.factory.order.FactoryOrderRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.OrderReworkDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryUpdateOrderDTO;
import com.zmn.oms.model.dto.work.modify.DuplicateOrderDTO;
import com.zmn.oms.model.dto.work.modify.CheckReworkOrderDTO;
import com.zmn.oms.model.dto.work.modify.other.ZsRemarkDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailVO;
import com.zmn.oms.services.interfaces.remark.OrderRemarkDetailService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.FactoryOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：厂商订单 remote service
 *
 * @author liuying
 * @date 2019/05/13 20:05
 */
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class FactoryOrderRemoteServiceImpl extends OrderBaseRemoteService implements FactoryOrderRemoteService {

	private Logger logger = LoggerFactory.getLogger(FactoryOrderRemoteServiceImpl.class);
	private static final String TAG = "啄木鸟-厂商订单";

	@Autowired
	ZsOrderWorkQueryBService zsOrderWorkQueryBService;
	@Autowired
	private FactoryOrderBService factoryOrderBService;
	@Autowired
	ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;
	@Autowired
	ZsNormalOrderBService zsNormalOrderBService;
	@Autowired
	private WorkFlowContextBService workFlowContextBService;
	@Autowired
	OrderWorkService orderWorkService;
	@Autowired
	OrderRemarkDetailService orderRemarkDetailServie;
	@Autowired
	OrderRemarkService orderRemarkService;
	@Autowired
	DuplicateOrderBService duplicateOrderBService;

	@Override
	public ResponseDTO<OrderWorkDRO> findOrderWorkByKey(Long orderId, Long workId) {
		logger.info("[{}] 查询订单：{}", TAG, orderId);
		try {
			OrderWork orderWorkByKey = orderWorkService.findOrderWorkByKey(orderId, workId);
			return ResponseUtil.responseSuccess(BeanMapper.map(orderWorkByKey,OrderWorkDRO.class), "OK");
		}
		catch (Exception e){
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	/**
	 * 修改订单
	 *
	 * @param updateOrderDIO 新单信息
	 * @return
	 */

	@Override
	public ResponseDTO updateOrder(UpdateOrderDIO updateOrderDIO) {
		logger.info("[{}] 修改订单：{}", TAG, updateOrderDIO);

		ValidateResult validateResult = ValidatorUtil.validator(updateOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}

		try {

			// 验证预约时间范围
			zsOrderWorkScheduleBService.validateDutyTime(updateOrderDIO.getOrderId(), updateOrderDIO.getPlat(), ConfOrderDutyConsts.TYPE_FACTORY, updateOrderDIO.getDutyTime());

			// DIO转换
			FactoryUpdateOrderDTO factoryUpdateOrderDTO = BeanMapper.map(updateOrderDIO, FactoryUpdateOrderDTO.class);

			// 操作人类型
			factoryUpdateOrderDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_FACTORY);

			// 修改
			factoryOrderBService.updateOrder(factoryUpdateOrderDTO);

			return ResponseUtil.responseSuccess("OK");

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 订单保存错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}

	}


	/**
	 * 新增订单
	 *
	 * @param fcNewOrderDIO 新单信息
	 * @return
	 */
	@Override
	public ResponseDTO<NewOrderDRO> addOrder(FcNewOrderDIO fcNewOrderDIO) {
		logger.info("[{}] 添加订单：{}", TAG, fcNewOrderDIO);

		ValidateResult validateResult = ValidatorUtil.validator(fcNewOrderDIO);
		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}

		try {

			// 验证预约时间范围
			zsOrderWorkScheduleBService.validateDutyTime(null, Optional.ofNullable(fcNewOrderDIO.getPlat()).orElse(GlobalConsts.PLAT_MARK_YEYX), ConfOrderDutyConsts.TYPE_FACTORY, fcNewOrderDIO.getDutyTime());

			// DIO转换
			FactoryNewOrderDTO newOrderDTO = BeanMapper.map(fcNewOrderDIO, FactoryNewOrderDTO.class);
			// 操作人类型
			newOrderDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_FACTORY);
			newOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
			logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.factory.order.FactoryOrderRemoteServiceImpl.addOrder]，厂商ID：[{}]，下单方式：[{}]", newOrderDTO.getOrderFactory().getFactoryId(), newOrderDTO.getReceiveEntranceId());
			OrderBO orderBO = factoryOrderBService.insertOrder(newOrderDTO);

			OrderWork orderWork = orderBO.getOrderWork();
			NewOrderDRO newOrderDRO = new NewOrderDRO();
			newOrderDRO.setWorkId(orderWork.getWorkId());
			newOrderDRO.setOrderId(orderWork.getOrderId());
			logger.info("[{}] 添加订单返回：{}", TAG, newOrderDRO);

			// 工单自动流转
			workFlowContextBService.asyncAutoFlow(orderWork.getOrderId(), orderWork.getWorkId());
			return ResponseUtil.responseSuccess(newOrderDRO, "OK");

		} catch (OmsBaseException ex) {
			return ResponseUtil.responseFail(ex.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("[{}] 订单保存错误：{}", TAG, e);
			return ResponseUtil.responseFail("添加订单失败");
		}

	}


	/**
	 * 查询厂商订单详情
	 *
	 * @param orderId
	 * @param workId
	 * @return
	 */
	@Override
	public ResponseDTO<FcOrderDetailDRO> findFcOrdeWorkDetail(Long orderId, Long workId) {
		logger.info("[{}] 查询订单：{}", TAG, orderId, workId);
		try {
            ZsOrderWorkDetailVO orderWorkDetail = zsOrderWorkQueryBService.findOrderWorkDetail(orderId, workId);
            FcOrderDetailDRO orderDetailDRO = BeanMapper.map(orderWorkDetail, FcOrderDetailDRO.class);
            orderDetailDRO.setOrderPostList(BeanMapper.mapList(orderWorkDetail.getOrderPostVOList(), OrderPostDRO.class));
			orderDetailDRO.setSuspendContent(orderWorkDetail.getDutyFailContent());

            return ResponseUtil.responseSuccess(orderDetailDRO,"OK");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[{}] 订单查询错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
	}

	/**
	 * 查询厂商订单列表
	 *
	 * @param queryDIO
	 * @return
	 */
	@Override
	public ResponseDTO<OrderListPageDRO> listPageOrderWorkByQuery(OrderQueryDIO queryDIO) {

		logger.info("[{}] 查询订单：{}", TAG, queryDIO);

		ValidateResult validateResult = ValidatorUtil.validator(queryDIO);

		if (!validateResult.isSuccess()) {
			logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
			return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
		}

		try {
			OrderWorkQuery orderWorkQuery = BeanMapper.map(queryDIO, OrderWorkQuery.class);

			// 是否挂起
			if (Objects.equals(GlobalConsts.YES, queryDIO.getSuspendStatus())) {
				orderWorkQuery.setIsDutySuspend(GlobalConsts.YES);
			}

			ResponseDTO<OrderListPageDRO> orderListPageDROResponseDTO = super.listOrder(orderWorkQuery);
			return orderListPageDROResponseDTO;

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 订单保存错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}

	}

	/**
	 * 保存备注
	 *
	 * @param fcRemarkDIO
	 * @return
	 */
	@Override
	public ResponseDTO saveRemark(FcRemarkDIO fcRemarkDIO) {

		try {
			ZsRemarkDTO zsRemarkDTO = BeanMapper.map(fcRemarkDIO, ZsRemarkDTO.class);
			zsNormalOrderBService.saveFactoryRemark(zsRemarkDTO);
			return ResponseUtil.responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 备注保存错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	/**
	 * 获取默认预约时间
	 *
	 * @return
	 */
	@Override
	public ResponseDTO getDefaultDutyTime() {
		try {
			String dutyTime = zsOrderWorkScheduleBService.getDefaultDutyTime(GlobalConsts.PLAT_MARK_YEYX, OrderGateTypeConsts.GATE_PORTAL_FC);
			return ResponseUtil.responseSuccess(dutyTime, "OK");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[{}] 获取默认预约时间错误：{}", TAG, e);
			return ResponseUtil.responseFail(e.getMessage());
		}
	}


	/**
	 * 获取预约时间
	 *
	 * @return
	 */
	@Override
	public ResponseDTO<OrderScheduleDayDRO> getScheduleDayList() {
		return super.getScheduleDayList();

	}

	/**
	 * 获取预约时间
	 *
	 * @param scheDate
	 * @return
	 */
	@Override
	public ResponseDTO<OrderScheduleTimeDRO> getScheduleTimes(String scheDate) {
		return super.getScheduleTimes(scheDate);
	}

	/**
	 * 获取预约时间--含平台类型
	 *
	 * @param gateScheduleDIO
	 * @return
	 */
	@Override
	public ResponseDTO<OrderScheduleTimeDRO> getScheduleTimes(GateScheduleDIO gateScheduleDIO) {
		return super.getScheduleTimes(gateScheduleDIO);
	}

	/**
	 * 检查返修单号
	 */
	@Override
	public ResponseDTO checkRework(CheckReworkOrderDIO checkReworkOrderDIO) {
		try {
			CheckReworkOrderDTO checkReworkOrderDTO = BeanMapper.map(checkReworkOrderDIO, CheckReworkOrderDTO.class);
			// 厂商id映射渠道id
			Integer channelId = super.getChannelIdByFcId(checkReworkOrderDIO.getFactoryId());
			checkReworkOrderDTO.setChannelId(channelId);

			// 同步检查新的返修单号的逻辑 xwb 2019.10.29
			OrderReworkDTO orderReworkDTO = zsNormalOrderBService.checkReworkId(checkReworkOrderDTO);
			CheckReworkOrderDRO orderReworkDRO = BeanMapper.map(orderReworkDTO,CheckReworkOrderDRO.class);
			return ResponseUtil.responseSuccessData(orderReworkDRO);
		} catch (OmsBaseException e) {
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	/**
	 * 厂商ID-> 渠道ID
	 */
	@Override
	public ResponseDTO<Integer> getChannelIdByFactoryId(Integer factoryId)  {
		try {
			return ResponseUtil.responseSuccess(super.getChannelIdByFcId(factoryId), "成功");
		}catch (OmsBaseException e) {
			logger.error("厂商ID转换渠道ID报错 {}", e.getMessage());
			return ResponseUtil.responseFail(e.getMessage());
		}
	}

	/**
	 * 校验15天内是否有重复工单 15天内用户电话、用户地址、服务分类、服务产品完全一致的
	 */
	@Override
	public ResponseDTO<Boolean> checkDuplicate(FcNewOrderDIO fcNewOrderDIO) {
		return ResponseUtil.responseSuccess(false, "成功");
	}

}
